package com.atguigu.security.filter;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.jwt.JwtHelper;
import com.atguigu.common.result.ResponseUtil;
import com.atguigu.common.result.Result;
import com.atguigu.common.result.ResultCodeEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * ClassName: TokenAuthenticationFilter
 * Package: com.atguigu.security.filter
 *
 * @Author: lmf
 * @Create: 2024/1/21 13:50
 * @Version: 1.0
 * Description:  认证解析token
 */
public class TokenAuthenticationFilter  extends OncePerRequestFilter {
    private RedisTemplate redisTemplate;
    public TokenAuthenticationFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     *  接口访问前验证
     */
    @Override
    protected void doFilterInternal
            (HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        //如果是登录接口，直接放行
        if("/admin/system/login/login".equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }

        // 用户是否登录过
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if(null != authentication) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.PERMISSION));
        }
    }

    /**
     *  接口访问前验证
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token置于header里
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            String username = JwtHelper.getUsername(token);
            if (!StringUtils.isEmpty(username)) {
                // 通过用户名称获取redis的权限数据
                final String authString = (String)redisTemplate.opsForValue().get(username);
                // 把redis获取字符串转换成需要的类型
                if (!StringUtils.isEmpty(authString)) {
                    final List<Map> mapList = JSON.parseArray(authString, Map.class);
                    final ArrayList<SimpleGrantedAuthority> authList = new ArrayList<>();
                    for (Map map : mapList) {
                        String auth = (String) map.get("authority");
                        authList.add(new SimpleGrantedAuthority(auth));
                    }
                    return new UsernamePasswordAuthenticationToken(username, null, authList);
                }
                return new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
            }
        }
        return null;
    }
}
